<template>
  <div
    :class="{ fullscreen: fullscreen }"
    class="tinymce-container"
    :style="{ width: containerWidth }"
  >
    <textarea :id="tinymceId" class="tinymce-textarea" />
    <!-- <div class="editor-custom-btn-container">
      <editorImage color="#1890ff" class="editor-upload-btn" @successCBK="imageSuccessCBK" />
    </div> -->
  </div>
</template>

<script>
/**
 * docs:
 * https://panjiachen.github.io/vue-element-admin-site/feature/component/rich-editor.html#tinymce
 */
import editorImage from './components/EditorImage'
import plugins from './plugins'
import toolbar from './toolbar'
import load from './dynamicLoadScript'

// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
const tinymceCDN =
  'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.3/tinymce.min.js'
// https://appint-cdn-axcje3cxhwe6aeha.z01.azurefd.net/cdn/tinymce@4.9.2/tinymce.min.js
export default {
  name: 'Tinymce',
  components: { editorImage },
  props: {
    id: {
      type: String,
      default: function () {
        return (
          'vue-tinymce-' +
          +new Date() +
          ((Math.random() * 1000).toFixed(0) + '')
        )
      }
    },
    value: {
      type: String,
      default: ''
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return []
      }
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table'
    },
    height: {
      type: [Number, String],
      required: false,
      default: 360
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto'
    },
    theme: {
      type: String,
      default: 'lightmode'
    },
    contentModel: {
      type: String,
      default:''
    }
  },
  data() {
    return {
      hasChange: false,
      hasInit: false,
      tinymceId: this.id,
      fullscreen: false,
      languageTypeList: {
        en: 'en',
        zh: 'zh_CN',
        es: 'es_MX',
        ja: 'ja'
      }
    }
  },
  computed: {
    containerWidth() {
      const width = this.width
      if (/^[\d]+(\.[\d]+)?$/.test(width)) {
        // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    }
  },
  watch: {
    value(val) {
      if (!this.hasChange && this.hasInit) {
        this.$nextTick(() => {
          window.tinymce.get(this.tinymceId).setContent(val || '')
        })
      }
    },
    theme() {
      this.destroyTinymce()
      this.initTinymce()
    }
  },
  mounted() {
    this.init()
  },

  activated() {
    if(this.contentModel!=='text') {
      if (window.tinymce) {
        this.initTinymce()
      }
    }
  },
  deactivated() {
    if(this.contentModel!=='text'){
      this.destroyTinymce()
    }
  },
  destroyed() {
    if(this.contentModel!=='text'){
      this.destroyTinymce()
    }
  },
  methods: {
    init() {
      // dynamic load tinymce from cdn
      load(tinymceCDN, err => {
        if (err) {
          this.$message.error(err.message)
          return
        }
        this.initTinymce()
      })
    },
    retryRender(val) {
      this.$nextTick(() => {
         window.tinymce.get(this.tinymceId).setContent(val || '')
      })
    },
    initTinymce() {
      const _this = this

      window.tinymce.init({
        selector: `#${this.tinymceId}`,
        branding:false,
        language: this.languageTypeList['en'],
        height: this.height,
        body_class: 'panel-body ',
        content_style:
          _this.theme === 'darkmode'
            ? `body { color: #fff;background-color: #292929; }`
            : `body { color: #1e1e1e;background-color: #fff; }`,
        object_resizing: false,
        toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
        menubar: this.menubar,
        menu: {},
        plugins: plugins,
	      forced_root_block: false,
        force_br_newlines: this.contentModel==='text',
        force_p_newlines: this.contentModel!== 'text',
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        paste_data_images: true,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          if (_this.value) {
            let value = _this.value
            if(this.contentModel==='text') {
              value = _this.value.replace(/\n/g, '<br>')
            }
            editor.setContent(value)
          }
          _this.hasInit = true
          editor.on('NodeChange Change KeyUp SetContent', () => {
            _this.hasChange = true
            _this.$emit('input', editor.getContent({format: this.contentModel}))
            _this.$emit('change', editor.getContent({format: this.contentModel}))
          })
        },
        setup(editor) {
          editor.on('FullscreenStateChanged', e => {
            _this.fullscreen = e.state
          })
          editor.addButton('slack-bold', {
            // text: 'Bold',
            icon: 'bold',
            onclick: function() {
              let selectedText = editor.selection.getContent({format: 'text'});
              let newText = '*' + selectedText + '*';
              editor.selection.setContent(newText);
            }
          });
          editor.addButton('slack-italic', {
            // text: 'Bold',
            icon: 'italic',
            onclick: function() {
              let selectedText = editor.selection.getContent({format: 'text'});
              let newText = '_' + selectedText + '_';
              editor.selection.setContent(newText);
            }
          });
          editor.addButton('slack-strike-through', {
            // text: 'Bold',
            icon:'slack-strike-through',
            onclick: function() {
              let selectedText = editor.selection.getContent({format: 'text'});
              let newText = '~' + selectedText + '~';
              editor.selection.setContent(newText);
            }
          });
          editor.addButton('slack-link', {
            // text: 'My button',
            icon: 'link',
            onclick: function () {
              editor.windowManager.open({
                title: 'Insert Link',
                body: [
                  { type: 'textbox', name: 'text', label: 'Display Text' },
                  { type: 'textbox', name: 'url', label: 'URL' }
                ],
                onsubmit: function (e) {
                  if (e.data.text.trim() === '') {
                    editor.windowManager.open({
                      title: 'Warning',
                      body: [
                        {
                          type: 'label',
                          text: 'Display Text cannot be empty'
                        }
                      ],
                      buttons: [
                        {
                          text: 'OK',
                          onclick: 'close'
                        }
                      ]
                    });
                    return false;
                  }

                  if (e.data.url.trim() === '') {
                    editor.windowManager.open({
                      title: 'Warning',
                      body: [
                        {
                          type: 'label',
                          text: 'URL cannot be empty'
                        }
                      ],
                      buttons: [
                        {
                          text: 'OK',
                          onclick: 'close'
                        }
                      ]
                    });
                    return false;
                  }
                  if(e.data.url.includes('http')) {
                    editor.insertContent(`<${e.data.url}|${e.data.text}>`);
                  }else {
                    editor.windowManager.open({
                      title: 'Warning',
                      body: [
                        {
                          type: 'label',
                          name: 'message',
                          text: 'The URL you entered seems to be an external link. Do you want to add the required http:// prefix?'
                        }
                      ],
                      buttons: [
                        {
                          text: 'Ok',
                          onclick: function () {
                            editor.insertContent(`<http://${e.data.url}|${e.data.text}>`);
                            editor.windowManager.close();
                          }
                        },
                        {
                          text: 'Cancel',
                          onclick: function () {
                            editor.insertContent(`<${e.data.url}|${e.data.text}>`);
                            editor.windowManager.close();
                          }
                        }
                      ]
                    });
                  }
                }
              });
            }
          });
        },

        convert_urls: false
      })
    },
    destroyTinymce() {
      const tinymce = window.tinymce.get(this.tinymceId)
      if (this.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }

      if (tinymce) {
        tinymce.destroy()
      }
    },
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value)
    },
    getContent() {
      return window.tinymce.get(this.tinymceId).getContent({format: this.contentModel})
    },
    imageSuccessCBK(arr) {
      arr.forEach(v =>
        window.tinymce
          .get(this.tinymceId)
          .insertContent(`<img class="wscnph" src="${v.url}" >`)
      )
    },
    getRng() {
      return window.tinymce.get(this.tinymceId).selection.getRng()
    },
    focus() {
      window.tinymce.get(this.tinymceId).focus()
    }
  }
}
</script>

<style lang="scss" scoped>
.tinymce-container {
  position: relative;
  line-height: normal;
}

.tinymce-container {
  ::v-deep {
    .mce-fullscreen {
      z-index: 10000;
    }
  }
}

.tinymce-textarea {
  visibility: hidden;
  z-index: -1;
}

.editor-custom-btn-container {
  position: absolute;
  right: 4px;
  top: 4px;
  /*z-index: 2005;*/
}

.fullscreen .editor-custom-btn-container {
  z-index: 10000;
  position: fixed;
}

.editor-upload-btn {
  display: inline-block;
}
</style>
<style lang="scss">
.mce-i-slack-strike-through {
  background-image: url('')!important;;
  background-size: auto!important;
}
</style>
